﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：DicCategoryDomainServcie.cs
// 功能描述：TongTongMall.MallWeb.Core
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.MallWeb.Core.Components.Models;
using TongTongMall.MallWeb.Core.IRepositories;

namespace TongTongMall.MallWeb.Core.Components.Services
{
    public class DicCategoryDomainServcie : TongTongMallDomainServiceBase, IDicCategoryDomainServcie
    {
        private readonly ICategoryRepository _categoryRespository;
        public DicCategoryDomainServcie(ICategoryRepository _categoryRespository)
        {
            this._categoryRespository = _categoryRespository;
        }

        public async Task<List<DicCategoryDto>> GetDicCategoryDtoTreeList(long tenantId)
        {
            var sourceList = await _categoryRespository.GetProductCategoryList(tenantId);
            var decorateTreeList = new List<DicCategoryDto>();
            foreach (var item in sourceList.Where(x => x.PCateID == null).ToList())
            {
                decorateTreeList.Add(SetChildrenList(item, sourceList));
            }
            return decorateTreeList;
        }

        

        /// <summary>
        /// 递归包装树形结构数据，可优化
        /// </summary>
        /// <param name="children"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        private DicCategoryDto SetChildrenList(DicCategoryDto children, List<DicCategoryDto> source)
        {
            children.List = (from p in source where p.PCateID == children.CateID select p).ToList();
            foreach (var item in children.List)
            {
                if (source.Where(x => x.PCateID == item.CateID).Count() > 0)
                {
                    if (item.List == null) item.List = new List<DicCategoryDto>();
                    item.List.Add(SetChildrenList(item, source));
                }
            }
            return children;
        }
    }
}
